<template>
	<w-dailog
		v-model="dialogVisible"
		width="1000px"
		:title="title"
		fullscreen
		:showMoreBtn="false"
		:beforeClose="onBeforeClose"
		@close="onRefresh"
	>
    <template slot="sub">
			<fx-detials-state-tag :label="currentState.label" :icon="currentState.icon"></fx-detials-state-tag>
		</template>
		<div class="create-organ" slot-scope="{ fullScreen }">
			<w-scroll-bar :flex="fullScreen">
        <basicInfo
					ref="basicInfo"
					:visibleFlag="dialogVisible"
					:programDetails="programDetails"
					:FactoryList="factoryList"
					:disabled="isChecked"
					@changeFactory="changeFactory"
				></basicInfo>
        <detailsInfo
					ref="detailsInfo"
					:disabled="isChecked"
					:fSaveMain="onSaveClickHandler"
					:programDetails="programDetails"
					:tableDetails="tableDetails"
					:itemList="itemList"
					@on-details-refresh="onDetailsRefresh"
				></detailsInfo>
			</w-scroll-bar>
		</div>
		<template slot="footer">
			<el-button @click="onCancelClick">取消</el-button>
			<fx-button v-show="!isChecked" type="save" @click="onSaveClick">保存</fx-button>
      <fx-button v-show="isState(['unChecked'])" type="check" @click="onCheckClick">审核</fx-button>
			<fx-button v-show="isState(['checked'])" type="uncheck" @click="onUncheckClick">反审</fx-button>
		</template>
	</w-dailog>
</template>
<script>
import basicInfo from './BasicInfo.vue'
import detailsInfo from './DetailsInfo.vue'
export default {
	name: 'createProgram',
	components: {
		basicInfo,
		detailsInfo
	},
	data () {
		return {
			title: '',
			dialogVisible: false,
			programDetails: {},
			factoryList: [],
			tableDetails: [],
			itemList: [],
			fxDataVerification: this.$fxUtils.fxDataVerification()
		}
	},
	computed: {
		isAdd () {
			return !this.programDetails.id
		},
		currentState () {
			return this.$fxStateMiddleware.getOrderStateById(this.programDetails.busState)
		},
		isChecked () {
			return this.$fxStateMiddleware.isState('billState')(['checked'])(this.programDetails.busState)
		},
		isState () {
			return (type) => {
				return this.$fxStateMiddleware.isState('billState')(type)(this.programDetails.busState)
			}
		}
	},
	methods: {
		async add (organType, treeNode, rootData) {
			const planDate = this.$fxUtils.setDateTime(new Date(), '时分')
			const nextCode = await this.getNextCode()
			const factoryList = await this.getListData()
			if (factoryList.length > 0) {
				this.itemList = await this.getMaterialList(factoryList[0].id)
			}
			this.programDetails = {
				id: '',
				code: nextCode,
				factoryId: factoryList.length > 0 ? factoryList[0].id : '',
				factoryOldId: factoryList.length > 0 ? factoryList[0].id : '',
				productionPlanDate: planDate,
				receivedDate: planDate,
				createUserName: '',
				createDate: planDate,
				auditUser: '',
				auditDate: '',
				importType: '0',
				remark: '',
				busState: 0
			}
			this.tableDetails = []
			this.factoryList = factoryList
			// if (this.programDetails.factoryId) {
			// 	this.itemList = await this.getMaterialList(this.programDetails.factoryId)
			// }
			// this.itemList = itemList
			this.fxDataVerification.resetData(this.programDetails)
			this.title = '新建生产计划'
			this.dialogVisible = true
			if (this.$refs.detailsInfo) {
				this.$refs.detailsInfo.$refs.detailsTable.clearSearchKey()
			}
		},
		async edit (programDetails, tableDetails) {
			const factoryList = await this.getListData()
			this.programDetails = programDetails
			this.programDetails.factoryOldId = programDetails.factoryId
			const itemList = await this.getMaterialList(this.programDetails.factoryId)
			this.itemList = itemList
			this.tableDetails = tableDetails.map(p => {
				const filterItem = itemList.filter(item => {
					if (item.id === p.materialId) {
						return item
					}
				})
				return {
					item: {
						id: p.materialId,
						code: p.materialCode,
						name: p.materialName
					},
					lineInfo: {
						id: p.lineId,
						code: p.lineCode
					},
					itemUnit: {
						id: p.materialUnitId,
						busUnit: p.materialUnitName
					},
					itemUnitList: filterItem[0].technologyMaterialUnitEntirys || [],
					lineList: filterItem[0].technologyLineEntirys || [],
					...p
				}
			})
			this.factoryList = factoryList
			// this.itemList = itemList
			this.fxDataVerification.resetData(this.programDetails)
			this.title = '编辑生产计划'
			this.dialogVisible = true
			if (this.$refs.detailsInfo) {
				this.$refs.detailsInfo.$refs.detailsTable.clearSearchKey()
			}
		},
		async getListData () {
			return Promise.all([this.getFactoryList()]).then(([factoryList]) => {
				return factoryList
			})
		},
		async getNextCode () {
			return this.$fxApi('schedule.getNextCode').then(nextCode => {
				return nextCode
			})
		},
		// 获取工厂下拉
		getFactoryList () {
			return this.$fxApi('workshop.findFactoryList')
		},
		// 获取物料行编辑下拉
		async getMaterialList (factoryId) {
			return this.$fxApi('routing.findProLineListByEnable')({
				query: {
					factoryId: factoryId
				}
			}).then(material => {
				return material
			})
		},
		// 保存按钮
		onSaveClick () {
			this.$refs.detailsInfo.checkDetailsUnSaving().then(() => {
				if (this.fxDataVerification.checkData(this.programDetails)) {
					this.$fxMessage.success('保存成功')
				} else {
					this.onSaveClickHandler()
				}
			})
		},
		onSaveClickHandler () {
			return this.onValidateFormData().then(this.onSaveProgramHandler)
		},
		onValidateFormData () {
			return new Promise(resolve => {
				this.$refs.basicInfo.validate().then(() => {
					resolve()
				}).catch(() => {
					this.$fxMessage.warning('请填写必填信息')
				})
			})
		},
		onSaveProgramHandler () {
			if (this.isAdd) {
				return this.$fxApi('schedule.saveOrUpdate')({ data: this.programDetails }).then(res => {
					this.$set(this.programDetails, 'id', res.id)
					this.fxDataVerification.resetData(this.programDetails)
					return Promise.resolve(res)
				})
			} else {
				if (this.fxDataVerification.checkData(this.programDetails)) {
					return Promise.resolve(this.programDetails)
				} else {
					return this.$fxApi('schedule.saveOrUpdate')({ data: this.programDetails }).then(res => {
						this.fxDataVerification.resetData(this.programDetails)
						return Promise.resolve(res)
					})
				}
			}
		},
		onCheckClick () {
			return this.beforeAction('是否确定审核？').then(() => {
				return this.$fxApi('schedule.auditOrBack', this.programDetails.id)({
					query: {
						opertion: 1
					}
				}).then(() => {
					// this.programDetails.busState = 1
					return this.onMainRefresh(this.programDetails.id).then(res => {
						this.programDetails = res
						this.fxDataVerification.resetData(this.programDetails)
					})
					// return Promise.resolve()
				})
			}).catch(err => err)
		},
		onUncheckClick () {
			return this.$fxConfirm('是否确定反审？').then(() => {
				return this.$fxApi('schedule.auditOrBack', this.programDetails.id)({
					query: {
						opertion: 0
					}
				}).then(() => {
					return this.onMainRefresh(this.programDetails.id).then(res => {
						this.programDetails = res
						this.fxDataVerification.resetData(this.programDetails)
					})
				})
			}).catch(err => err)
		},
		beforeAction (message) {
			return this.$fxConfirm(message).then(() => {
				return this.$refs.detailsInfo.checkDetailsUnSaving().then(this.onSaveClickHandler)
			})
		},
		// 刷新明细
		onDetailsRefresh () {
			return this.$fxApi('schedule.findProductionPlanDetail')({
				query: {
					productionPlanId: this.programDetails.id
				}
			}).then(res => {
				this.tableDetails = res
				return Promise.resolve(res)
			})
		},
		// 刷新主表
		onMainRefresh (planId) {
			return this.$fxApi('schedule.findDetailByParam')({
				query: {
					id: planId
				}
			}).then(res => {
				return Promise.resolve(res)
			})
		},
		// 取消
		onCancelClick () {
			this.verificationDetails().then(() => {
				this.onSaveClickHandler().then(() => {
					this.dialogVisible = false
				})
			}).catch(() => {
				this.dialogVisible = false
			})
		},
		onBeforeClose (close) {
			this.verificationDetails().then(() => {
				this.onSaveClickHandler().then(close)
			}).catch(() => {
				this.dialogVisible = false
			})
		},
		verificationDetails () {
			return this.fxDataVerification.checkComfirm(this.programDetails)
		},
		onRefresh () {
			this.$emit('on-refresh')
		},
		// 改变工厂 获取物料
		changeFactory (val) {
			this.onFactoryChangeConfirm().then(() => {
				this.clearDetails(val)
			}).catch(() => {
				this.programDetails.factoryId = this.programDetails.factoryOldId
			})
		},
		async clearDetails (val) {
			this.tableDetails = []
			this.programDetails.factoryOldId = val
			this.itemList = await this.getMaterialList(val)
		},
		onFactoryChangeConfirm () {
			return new Promise((resolve, reject) => {
				if (this.tableDetails.length === 0) {
					resolve()
				} else {
					this.$fxConfirm('该操作会清空明细数据，确定更换工厂？').then(() => {
						resolve()
					}).catch(() => {
						reject(new Error())
					})
				}
			})
		}
	}
}
</script>
<style lang="stylus" scoped>
@import '~$assets/stylus/varsty.styl'
.create-organ {
	flex: 1
	display: flex;
	flex-direction: column;
	overflow: auto;
}
</style>
